/**   
 * @Title: SynchronousFragment.java 
 * @Package: com.rename.icode.activity 
 * @Description: Administrator版权所有
 * @author Administrator  
 * @date 2015-2-11 下午2:47:54 
 * @version  
 */

package com.rename.icode.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.rename.icode.R;
import com.rename.icode.comm.Constants;
import com.rename.icode.manager.AppConfigManager;
import com.rename.icode.manager.UserManager;
import com.rename.icode.model.CodeFile;
import com.rename.icode.utils.HttpURLTools;
import com.rename.icode.utils.LogUtil;
import com.rename.icode.utils.StringUtil;
import com.rename.icode.view.CodeFilesAdapter;
import com.rename.icode.view.HorizontalListAdapter;
import com.rename.icode.view.HorizontalListView;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description 实现了...功能
 * @author WangXinMing
 * @date 2015-2-11 下午2:47:54
 * @version V1.0
 */

public class SynchronousFragment extends Fragment {

	private static final String TAG = "SynchronousFragment";
	private View mSynchronousFragmentView;
	private static SynchronousFragment mSynchronousFragment;
	private Context mContext;

	private ListView mFileList;
	private OnClickListener mFileOnClickListener;
	private CodeFilesAdapter mAdapter;
	private List<CodeFile> mCodeFiles = new ArrayList<CodeFile>();
	private SynchronousReceiver mReceiver;

	private LinearLayout mBottomLayout;
	private HorizontalListView mHorizontalListView;
	private HorizontalListAdapter mHorizontalListAdapter;
	private List<CodeFile> mSelectedCodeFiles = new ArrayList<CodeFile>();
	private CodeFile mUploadedCodeFile = null; // 上传完成的文件
	private Button mCfmBtn = null;

	private String mResult = null;
	private static final int UPLOADED = 0;
	private static final int ALL_UPLOADED = 1;
	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case UPLOADED: // 单个文件上传完成
				String filename = mUploadedCodeFile.getName();
				LogUtil.i(TAG, "上传的文件是" + filename);
				
				if (Constants.UPLOAD_SUCCESS.equals(mResult)) { // 上传成功
					LogUtil.i(TAG, "文件上传成功");
					Toast.makeText(mContext, filename + "文件上传成功", 0).show();
					mSelectedCodeFiles.remove(mUploadedCodeFile); // 水平列表数据更新
					mAdapter.updateSelection(mUploadedCodeFile, false); // 上传成功的文件设置为未选中
					LogUtil.i(TAG, "mSelectedCodeFiles size is "
							+ mSelectedCodeFiles.size());
					// adapter数据更新通知
					mAdapter.notifyDataSetChanged();
					mHorizontalListAdapter.notifyDataSetChanged();
				} else { // 上传失败
					// TODO
					Toast.makeText(mContext, filename + "文件上传失败", 0).show();
				}
				break;
			case ALL_UPLOADED: // 所有文件上传结束
				LogUtil.i(TAG, "文件上传结束");
				((MainActivity) mContext).pg.dismiss();

				// 上传按钮设置
				if (mSelectedCodeFiles.size() > 0) {
					Toast.makeText(mContext, "部分文件上传失败", 0).show();
					mCfmBtn.setClickable(true);
					mCfmBtn.setAlpha(1.0f);
				} else {
					Toast.makeText(mContext, "所有文件上传完成", 0).show();
					mCfmBtn.setClickable(false);
					mCfmBtn.setAlpha(0.7f);
				}

				refreshCodeFileListView(); // 刷新文件列表

				// 通知刷新ServerFragment文件列表
				Intent serverIntent = new Intent();
				serverIntent.setAction(Constants.SERVER_REFRESH);
				mContext.sendBroadcast(serverIntent);
				break;
			default:
				break;
			}
		}

	};

	public SynchronousFragment() {
		super();
	}

	public static SynchronousFragment getSynchronousFragmentIntance() {
		if (mSynchronousFragment != null) {
			return mSynchronousFragment;
		} else {
			mSynchronousFragment = new SynchronousFragment();
			return mSynchronousFragment;
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		mSynchronousFragmentView = inflater.inflate(R.layout.synchronous_info,
				container, false);

		init();
		return mSynchronousFragmentView;
	}

	private void init() {
		LogUtil.i(TAG, "SynchronousFragment init...");
		mContext = getActivity();

		mAdapter = new CodeFilesAdapter(mContext, mCodeFiles,
				CodeFilesAdapter.SELECT_MODE);
		mAdapter.setOnClickListener(mFileOnClickListener);
		mFileList = (ListView) mSynchronousFragmentView
				.findViewById(R.id.synchronous_list);
		mFileList.setAdapter(mAdapter);
		mFileList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				CodeFile codeFile = (CodeFile) (view
						.findViewById(R.id.file_name_txt).getTag());

				if (mSelectedCodeFiles.contains(codeFile)) {// 已经选中
					mSelectedCodeFiles.remove(codeFile);
					mAdapter.updateSelection(position, false);// 更新ListView中item选中情况
				} else {
					mSelectedCodeFiles.add(codeFile);
					mAdapter.updateSelection(position, true);
				}

				mCfmBtn.setText(getResources().getString(R.string.confirm)
						+ (mSelectedCodeFiles.size() > 0 ? "("
								+ mSelectedCodeFiles.size() + ")" : ""));
				if (mSelectedCodeFiles.size() > 0) {
					mCfmBtn.setClickable(true);
					mCfmBtn.setAlpha(1.0f);
				} else {
					mCfmBtn.setClickable(false);
					mCfmBtn.setAlpha(0.7f);
				}
				// adapter数据更新通知
				mAdapter.notifyDataSetChanged();
				mHorizontalListAdapter.notifyDataSetChanged();

			}
		});

		mBottomLayout = (LinearLayout) mSynchronousFragmentView
				.findViewById(R.id.files_buttom_lay);

		mHorizontalListAdapter = new HorizontalListAdapter(mContext,
				mSelectedCodeFiles);
		mHorizontalListView = (HorizontalListView) mSynchronousFragmentView
				.findViewById(R.id.selected_file_list);
		mHorizontalListView.setAdapter(mHorizontalListAdapter);
		mHorizontalListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				CodeFile codeFile = (CodeFile) (view
						.findViewById(R.id.selected_file_name_txt).getTag());

				if (mSelectedCodeFiles.contains(codeFile)) {// 已经选中
					mSelectedCodeFiles.remove(codeFile);
					mAdapter.updateSelection(codeFile, false);// 更新ListView中item选中情况
				} else {
					mSelectedCodeFiles.add(codeFile);
					mAdapter.updateSelection(codeFile, true);
				}

				mCfmBtn.setText(getResources().getString(R.string.confirm)
						+ (mSelectedCodeFiles.size() > 0 ? "("
								+ mSelectedCodeFiles.size() + ")" : ""));
				if (mSelectedCodeFiles.size() > 0) {
					mCfmBtn.setClickable(true);
					mCfmBtn.setAlpha(1.0f);
				} else {
					mCfmBtn.setClickable(false);
					mCfmBtn.setAlpha(0.7f);
				}
				// adapter数据更新通知
				mAdapter.notifyDataSetChanged();
				mHorizontalListAdapter.notifyDataSetChanged();
			}
		});

		mCfmBtn = (Button) mSynchronousFragmentView
				.findViewById(R.id.confirm_btn);
		mCfmBtn.setClickable(false);
		mCfmBtn.setAlpha(0.7f);
		mCfmBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				((MainActivity) mContext).pg.setTitle("正在上传...");
				((MainActivity) mContext).pg.show();
				new Thread() {

					@Override
					public void run() {

						for (CodeFile codeFile : mSelectedCodeFiles) {
							mUploadedCodeFile = codeFile;
							mResult = HttpURLTools.postFile(
									Constants.UPLOAD_URL, codeFile.getPath(),
									UserManager.getInstance().getUser()
											.getName());
							LogUtil.i(TAG, "upload codeFile.getPath() is "
									+ codeFile.getPath());
							LogUtil.i(TAG, "upload username is "
									+ UserManager.getInstance().getUser()
											.getName());
							LogUtil.i(TAG, "upload mResult is " + mResult);
							mHandler.sendEmptyMessage(UPLOADED);
						}
						UserManager.getInstance().refreshSeverData(); // 重新请求刷新服务器文件
						// 测试
						for (CodeFile codeFile : mCodeFiles) {
							LogUtil.i("aa",
									"synchronousfragment文件刷新 codefile is "
											+ codeFile.getName());
						}
						mHandler.sendEmptyMessage(ALL_UPLOADED);
					}

				}.start();

			}
		});

	}

	private class SynchronousReceiver extends BroadcastReceiver {

		/**
		 * Description
		 * 
		 * @param context
		 * @param intent
		 * @see android.content.BroadcastReceiver#onReceive(android.content.Context,
		 *      android.content.Intent)
		 */

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();

			if (Constants.LOCAL_REFRESH.equals(action)) {
				LogUtil.i(TAG, "LOCAL_REFRESH...");
				refreshCodeFileListView();
			}
		}

	}

	private void refreshCodeFileListView() {
		mCodeFiles = UserManager.getInstance().getUser().getLocalData();
		mAdapter.refreshList(mCodeFiles);
	}

	private void initReceiver() {
		if (null == mReceiver) {
			mReceiver = new SynchronousReceiver();
			IntentFilter intentFilter = new IntentFilter();
			intentFilter.addAction(Constants.LOCAL_REFRESH);
			mContext.registerReceiver(mReceiver, intentFilter);
		}
	}

	@Override
	public void onResume() {
		super.onResume();
		initReceiver();
		if (Constants.GUEST
				.equals(AppConfigManager.getInstance().getUsername())) {
			mBottomLayout.setVisibility(View.GONE);
		} else {
			refreshCodeFileListView();
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		mContext.unregisterReceiver(mReceiver);
		mReceiver = null;
	}

}
